<template>
  <div style="padding: 20px">
    <!-- 头部 -->
    <div class="header">
      <div style="width: 30%; display: flex; align-items: center">
        <div style="width: 120px">用户名称：</div>
        <el-input v-model="pageData.keyword" />
      </div>
      <div class="buttons">
        <el-button @click="getList">搜索</el-button>
        <el-button @click="reSet">重置</el-button>
        <el-button @click="addClick">新增</el-button>
      </div>
    </div>
    <!-- 表格 -->
    <el-table max-height="520" :data="list" border style="width: 100%">
      <el-table-column
        fixed
        type="index"
        label="#"
        width="100"
        align="center"
      />
      <el-table-column label="id" width="120" prop="id" align="center" />
      <el-table-column label="用户名" width="180" prop="name" align="center" />
      <el-table-column label="角色" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.is_admin === '1'">超级管理员</el-tag>
          <el-tag
            type="success"
            v-if="options.filter((option) => option.value == item).length"
            v-for="(item, index) in scope.row.role_id_array"
            :key="index"
          >
            {{ options.filter((option) => option.value == item)[0].label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created_at" align="center" />
      <el-table-column label="更新时间" prop="updated_at" align="center" />
      <!-- 操作 -->
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <div style="display: flex; justify-content: space-evenly">
            <el-button
              @click="editThis(scope.row)"
              type="primary"
              icon="el-icon-edit"
              circle
            ></el-button>
            <el-button
              :disabled="scope.row.is_admin === '1'"
              @click="setroleShow(scope.row)"
              type="warning"
              icon="el-icon-star-off"
              circle
            ></el-button>
            <el-button
              @click="deleThis(scope.row.id)"
              type="danger"
              icon="el-icon-delete"
              circle
            ></el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <div class="foot">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageData.page"
        :page-sizes="[10, 15, 20]"
        :page-size="pageData.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
      >
      </el-pagination>
    </div>
    <!-- 新增和编辑公用的弹窗 -->
    <el-dialog
      :title="isEdit ? '编辑用户' : '新增用户'"
      :visible.sync="dialogFormVisible"
      width="50%"
    >
      <el-form :rules="rules" ref="adminForm" status-icon :model="adminForm">
        <el-form-item label="用户" prop="name">
          <el-input v-model="adminForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="adminForm.password" type="password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="sub">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog
      @close="roleClear"
      title="分配角色"
      :visible.sync="roleShow"
      width="50%"
    >
      <el-select
        style="width: 55%"
        v-model="roleIds"
        multiple
        placeholder="请选择角色"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleShow = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
  
<script>
import { listRole } from "@/api/role";
import { getAdminList, addAdmin, editAdmin, deleteAdmin } from "@/api/admin";
export default {
  name: "AdminManagement",
  data() {
    return {
      list: [], //表格数据
      pageData: {
        limit: 10,
        page: 1,
        keyword: "",
      },
      isEdit: false, //判断新增还是添加的字段
      count: 0, //总条数
      dialogFormVisible: false,
      adminForm: {
        //表单数据
        name: "",
        password: "",
      },
      rules: {
        name: [{ required: true, trigger: "blur", message: "请输入用户名" }],
        password: [{ required: true, trigger: "blur", message: "请输入密码" }],
      },
      roleShow: false, //分配角色弹窗显隐
      options: [], //选择器的选项
      roleIds: [], //分配角色的ids
      onId: "", //要分配角色的id
    };
  },
  methods: {
    //获取表格数据
    async getList() {
      let res = await getAdminList(this.pageData);
      let { data } = res;
      this.list = data.list;
      this.count = data.count;
    },
    //重置
    reSet() {
      this.pageData.keyword = "";
      this.getList();
    },
    //每页条数变化
    handleSizeChange(size) {
      this.pageData.limit = size;
      this.getList();
    },
    //当前页发生变化
    handleCurrentChange(page) {
      this.pageData.page = page;
      this.getList();
    },
    //删除数据
    deleThis(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteAdmin({ id });
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //添加和编辑角色
    sub() {
      this.$refs.adminForm.validate(async (valid) => {
        if (valid) {
          if (this.isEdit) {
            //编辑
            await editAdmin(this.adminForm);
            this.$message({
              message: "编辑成功",
              type: "success",
            });
          } else {
            //添加
            await addAdmin(this.adminForm);
            this.$message({
              message: "成功添加",
              type: "success",
            });
          }
          this.dialogFormVisible = false;
          this.getList(); //刷新列表
        }
      });
    },
    //点击编辑按钮
    editThis(row) {
      this.isEdit = true;
      this.dialogFormVisible = true;
      this.adminForm = {
        //数据回显
        name: row.name,
        password: "",
        id: row.id,
      };
    },
    // 点击新增按钮
    addClick() {
      this.isEdit = false;
      this.dialogFormVisible = true;
    },
    //设置角色
    async setRole() {
      await editAdmin({ id: this.onId, role_ids_array: this.roleIds });
      this.$message({
        type: "success",
        message: "设置角色成功!",
      });
      this.roleShow = false; //关闭弹窗
      this.getList(); //刷新数据
    },
    //角色弹窗关闭的回调
    roleClear() {
      this.roleIds = [];
    },
    //点击按钮设置角色弹窗显示
    setroleShow(row) {
      console.log(row);
      this.roleShow = true;
      //存个id
      this.onId = row.id;
      //数据回显
      this.roleIds = row.role_id_array.filter((item) => item) || [];
    },
  },
  created() {
    this.getList();
  },
  async mounted() {
    let { data } = await listRole({ limit: 100, page: 1 });
    this.options = data.list.map((item) => {
      return { value: item.id.toString(), label: item.name };
    });
  },
  //监听
  watch: {
    dialogFormVisible() {
      //变为false时清空表单数据
      if (!this.dialogFormVisible) {
        this.adminForm = {
          name: "",
          password: "",
        };
      }
    },
  },
};
</script>
  
<style scoped lang="scss">
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.foot {
  margin-top: 10px;
  float: right;
}
</style>